package cn.ipanel.bigdata.boot

import cn.ipanel.bigdata.boot.date.Time
import cn.ipanel.bigdata.boot.logger.Logger

/**
 * Author: lzz
 * Date: 2021/12/23 10:33
 */
class JobMonitor(jobName: String, maxRuntime: Int) extends Runnable {

  import Application._

  var started: Boolean = false
  val WAIT_TIME: Int = 3 * 1000

  def open(): Unit = {
    if (!started) {
      new Thread(JobMonitor.this, s"$jobName-monitor").start()
      started = !started
    }
  }

  def quit(): Unit = {
    if (started)
      started = !started
  }

  override def run(): Unit = {
    val now = Time.now
    val max = maxRuntime * 60 * 1000
    while (started && max > 0) {
      Logger.I(s"job[$jobName] runtime = ${now.diffToNow / 1000}sec")
      if (now.diffToNow > max) {
        started = false
        shutdown(RESULT_TIMEOUT)
      } else {
        Thread.sleep(WAIT_TIME)
      }
    }
  }
}